package com.ruoyi.framework.web.websocket;

import com.ruoyi.framework.web.websocket.config.WebSocketFilter;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * WebSocket基类
 */
public abstract class AbstractWebSocket {

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private final static ConcurrentHashMap<Class<?>, AtomicInteger> onlineCount = new ConcurrentHashMap<>();

    /**
     * 获取在线总数
     * @return
     */
    public int getOnlineCount(){
        return onlineCount.size();
    }

    /**
     * 客户端在线计数
     * @param count
     */
    protected synchronized void calcOnlineCount(int count) {
        Class<?> currentClass = this.getClass();
        AtomicInteger onLineCount = onlineCount.computeIfAbsent(currentClass, k -> new AtomicInteger(0));
        onLineCount.addAndGet(count);
    }

    /**
     * 获取客户端IP
     * @param config
     * @return
     */
    protected String getClientIpAddress(EndpointConfig config) {
        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        return httpSession.getAttribute(WebSocketFilter.IP_ATTR_NAME).toString();
    }
}
